﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using SLS.DataBase;
using SLS.ExClassLib.Events;
using SLS.ExClassLib.Message;
namespace SLS.ExClassLib.Database
{
    /// <summary>
    /// Class that holds everything that need to be binded to the main window
    /// </summary>
    public partial class DataAccessService
    {
        public Queue ConvertStr2Queue(string StrtoSplit)
        {
            Queue QueueOfStr = new Queue();
            int strPosX = 0;
            int iTmp = 0;
            string substr;

            while (StrtoSplit != "")
            {
                iTmp = StrtoSplit.Length;
                strPosX = StrtoSplit.IndexOf(";");
                substr = StrtoSplit.Substring(0, strPosX);
                StrtoSplit = StrtoSplit.Substring(strPosX + 1, iTmp - (strPosX + 1));
                QueueOfStr.Enqueue(substr);
            }
            return QueueOfStr;
        }
        public Object ImportDataTable(DataSet setTarget, DataRow rowSource)
        {
            DataTable tableTarget = null;
            try
            {
                if (rowSource != null)
                {
                    tableTarget = this.ImportDataRow(rowSource);
                    setTarget.Merge(tableTarget, true, MissingSchemaAction.Add);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error("DataAccessService.ImportDataTable", ex);
            }
            return setTarget;
        }
        public Object ImportDataTable(DataSet setTarget, DataTable tableSource)
        {
            try
            {
                setTarget.Merge(tableSource);
            }
            catch (Exception ex)
            {
                Tracer.Error("DataAccessService.ImportDataTable", ex);
            }
            return setTarget;
        }
        public void ImportDataTable(ref DataSet setTarget, DataTable tableSource)
        {
            try
            {
                setTarget.Merge(tableSource);
            }
            catch (Exception ex)
            {
                Tracer.Error("DataAccessService.ImportDataTable", ex);
            }
        }
        public void ImportDataTable(ref DataSet setTarget, DataRow rowSource)
        {
            DataTable tableTarget = null;
            try
            {
                if (rowSource != null)
                {
                    tableTarget = this.ImportDataRow(rowSource);
                    setTarget.Merge(tableTarget, true, MissingSchemaAction.Add);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error("DataAccessService.ImportDataTable", ex);
            }
        }
        public DataTable ImportDataRow(DataRow rowSource)
        {
            DataTable tableTarget = rowSource.Table.Clone();
            try
            {
                if (rowSource != null)
                {
                    tableTarget.Rows.Add(rowSource.ItemArray);
                    //                    objectTable.ImportRow(DataRowSrc);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error("DataAccessService.ImportDataRow", ex);
            }
            return tableTarget;
        }

        public void DeleteData(DataSet set2Delete)
        {
            try
            {
                MessageEx msgRequest = new MessageEx();
                MessageEx MsgReturn = new MessageEx();
                msgRequest.JobID = "OnDeleteRecord";
                msgRequest.setEvent = set2Delete;
                QueryData(msgRequest);
            }
            catch (Exception ex)
            {
                Tracer.Error("DataAccessService.DeleteData", ex);
            }
        }
        public DataSet GetLogInDataSet()
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            MessageEx msg = new MessageEx(BaseMessage);
            try
            {
                msg.JobID = "OnQueryAgentList";
                setResult = QueryData(msg);
                setReturn.Merge(setResult);
                setResult = LoadAgentDataSet();
                setReturn.Merge(setResult); 
            }
            catch (Exception ex)
            {
                Tracer.Error("DataAccessService.GetLogInDataSet", ex);
            }
            return setReturn;
        }
        public DataSet LoadAgentDataSet()
        {
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();

            try
            {
                setResult = GetDataByAny("SystemManagement", null);
                setReturn.Merge(setResult);
                setResult = GetDataByAny("UserManagement", null);
                setReturn.Merge(setResult);
                dwUser = setReturn.Tables["UserManagement"].NewRow();
                dwUser["SM"] = "1";
                dwUser["AGENTID"] = "LANSUN";
            }
            catch (Exception ex)
            {
                Tracer.Error("DataAccessService.LoadAgentDataSet", ex);
            }
            return setReturn;
        }
        public void UpdateForeignKeyList()
        {
            try
            {
                /*
                 * INSERT INTO "TableList2Agent"("UID", "", "SM", "TableID", "TBNAME", "AgentID", "AgentName", "Task", "TContent", "ShortName", "SUBSTATUS", "KeyCondition", "Status", "FUSER", "FDATE", "LUSER", "LDATE")
VALUES ('9100080LForeignKeyList', '9MenuForeignKeyList', '1', '100080', 'ForeignKeyList', 'LANSUN', 'LANSUN', 'DataChange', '', '  ', 'UPDATE', 'UPDATE', 'UPDATE', null, null, null, null)
GO
                 */
                DataTable dtTableList2Agent = GetTableList2Agent("DataChange", "ForeignKeyList");
                DataSet setReturn = new DataSet();
                if (dtTableList2Agent.Rows.Count > 0)
                {
                    foreach (DataRow dwTableList2Agent in dtTableList2Agent.Rows)
                    {
                        GlobalDataSet.Tables["ForeignKeyList"].Rows.Clear();
                        setReturn = GetDataBySM("ForeignKeyList");
                        GlobalDataSet.Merge(setReturn);
                        dwTableList2Agent["STATUS"] = "DELETE";
                    }
                    DataSet ds2Delete = new DataSet();
                    ds2Delete.Tables.Add(dtTableList2Agent.Clone());
                    foreach (DataRow dwTableList2Agent in dtTableList2Agent.Rows)
                    {
                        if (dwTableList2Agent["STATUS"].ToString().Trim() == "DELETE")
                        {
                            ds2Delete = (DataSet)ImportDataTable(ds2Delete, dwTableList2Agent);
                        }
                    }
                    ds2Delete.AcceptChanges();
                    DeleteData(ds2Delete);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error("DataAccessService.UpdateForeignKeyList", ex);
            }
        }
        public void BuildGUIProfile()
        {
            /*	GUIProfile是某种工作环境的定义，在这种工作环境下，设定每个表显示的格式GUIDesignTime
             * 创建字典，界面装载是直接装载字典
             */

        }
        public void UpdateGUIProfile()
        {
            try
            {
                /*
                 * INSERT INTO "TableList2Agent"("UID", "", "SM", "TableID", "TBNAME", "AgentID", "AgentName", "Task", "TContent", "ShortName", "SUBSTATUS", "KeyCondition", "Status", "FUSER", "FDATE", "LUSER", "LDATE")
                    VALUES ('9100GUIProfile', '9GUIProfile', '1', '100051', 'GUIProfile', 'LANSUN', 'LANSUN', 'DataChange', '', '  ', 'UPDATE', 'UPDATE', 'UPDATE', null, null, null, null)
                    GO
                 * */
                DataTable dtTableList2Agent = GetTableList2Agent("DataChange", "GUIProfile");
                DataSet setReturn = new DataSet();
                if (dtTableList2Agent.Rows.Count > 0)
                {
                    foreach (DataRow dwTableList2Agent in dtTableList2Agent.Rows)
                    {
                        GlobalDataSet.Tables["GUIProfile"].Rows.Clear();
                        setReturn = GetDataBySM("GUIProfile");
                        GlobalDataSet.Merge(setReturn);
                        dwTableList2Agent["STATUS"] = "DELETE";
                    }
                    DataSet ds2Delete = new DataSet();
                    ds2Delete.Tables.Add(dtTableList2Agent.Clone());
                    foreach (DataRow dwTableList2Agent in dtTableList2Agent.Rows)
                    {
                        if (dwTableList2Agent["STATUS"].ToString().Trim() == "DELETE")
                        {
                            ds2Delete = (DataSet)ImportDataTable(ds2Delete, dwTableList2Agent);
                        }
                    }
                    ds2Delete.AcceptChanges();
                    DeleteData(ds2Delete);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error("DataAccessService.UpdateGUIProfile", ex);
            }
        }
        public void UpdateGUIDesignTime()
        {
            /*
           * INSERT INTO "TableList2Agent"("UID", "", "SM", "TableID", "TBNAME", "AgentID", "AgentName", "Task", "TContent", "ShortName", "SUBSTATUS", "KeyCondition", "Status", "FUSER", "FDATE", "LUSER", "LDATE")
              VALUES ('GUIDesignTime', 'GUIDesignTime', '1', '100042', 'GUIDesignTime', 'LANSUN', 'LANSUN', 'DataChange', '', '  ', 'UPDATE', 'UPDATE', 'UPDATE', null, null, null, null)
              GO
           * */
            try
            {
                DataTable dtTableList2Agent = GetTableList2Agent("DataChange", "GUIDesignTime");
                DataSet setReturn = new DataSet();
                if (dtTableList2Agent.Rows.Count > 0)
                {
                    foreach (DataRow dwTableList2Agent in dtTableList2Agent.Rows)
                    {
                        GlobalDataSet.Tables["GUIDesignTime"].Rows.Clear();
                        setReturn = GetDataBySM("GUIDesignTime");
                        GlobalDataSet.Merge(setReturn);
                        dwTableList2Agent["STATUS"] = "DELETE";
                    }
                    DataSet ds2Delete = new DataSet();
                    ds2Delete.Tables.Add(dtTableList2Agent.Clone());
                    foreach (DataRow dwTableList2Agent in dtTableList2Agent.Rows)
                    {
                        if (dwTableList2Agent["STATUS"].ToString().Trim() == "DELETE")
                        {
                            ds2Delete = (DataSet)ImportDataTable(ds2Delete, dwTableList2Agent);
                        }
                    }
                    ds2Delete.AcceptChanges();
                    DeleteData(ds2Delete);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error("DataAccessService.UpdateGUIDesignTime", ex);
            }
        }
        public void UpdateGlobalDataSet()
        {
            try
            {

                this.UIXMLPath = AppXMLPath + "GlobalDataSet.XML";
                #region LoadFromSet2Load
                string set2loadfile = AppXMLPath + @"Set4UI.xml";

                SLDBSET set2Load = null;
                set2Load = new SLDBSET();
                if (File.Exists(set2loadfile))
                {
                    set2Load.ReadXml(set2loadfile);
                    File.Delete(set2loadfile);
                    if (File.Exists(UIXMLPath))
                    {
                        File.Delete(UIXMLPath);
                    }
                }
                GlobalDataSet.Merge(set2Load);

                #endregion
                #region LoadFromFile               
                DataSet setTemp = new DataSet();
                if (File.Exists(UIXMLPath))
                {
                    setTemp.ReadXml(UIXMLPath);
                    GlobalDataSet.Merge(setTemp);
                    return;
                }
                #endregion
                #region BuildGUIProfile
                BuildGUIProfile();
                #endregion

                #region SaveData
                GlobalDataSet.WriteXml(UIXMLPath, XmlWriteMode.WriteSchema);
                #endregion
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public DataTable GetTableList2Agent(string TaskType)
        {
            DataTable dtTableList2Agent = new DataTable();
            try
            {
                DataSet dsRequest = new DataSet();
                MessageEx msg = new MessageEx(BaseMessage);
                DataRow dwQueryCond = setQueryCond.Tables["TableList2AgentQueryCond"].NewRow();
                dwQueryCond["QUERYTYPE"] = "QueryOnly";
                dwQueryCond["CONDTYPE"] = "IX_TableList2Agent_TaskType";
                dwQueryCond["SM"] = dwUser["SM"];
                dwQueryCond["AGENTID"] = dwUser["AGENTID"];
                dwQueryCond["TASK"] = TaskType;
                dsRequest = (DataSet)ImportDataTable(dsRequest, dwQueryCond);
                msg.setEvent = dsRequest;
                msg.JobID = "OnQueryTableList2Agent";
                DataSet dsReturn = QueryData(msg);
                if (dsReturn.Tables.Contains("TableList2Agent"))
                {
                    dtTableList2Agent = dsReturn.Tables["TableList2Agent"].Copy();
                }

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return dtTableList2Agent;
        }
        public DataTable GetTableList2Agent(string TaskType, string TBNAME)
        {
            DataTable dtTableList2Agent = new DataTable();
            try
            {
                DataSet dsRequest = new DataSet();
                MessageEx msg = new MessageEx(BaseMessage);
                DataRow dwQueryCond = setQueryCond.Tables["TableList2AgentQueryCond"].NewRow();
                dwQueryCond["QueryType"] = "QueryOnly";
                dwQueryCond["CONDTYPE"] = "IX_TableList2Agent_TaskTypeByTBNAME";
                dwQueryCond["SM"] = dwUser["SM"];
                dwQueryCond["AGENTID"] = dwUser["AGENTID"];
                dwQueryCond["TASK"] = TaskType;
                dwQueryCond["TBNAME"] = TBNAME;
                dsRequest = (DataSet)ImportDataTable(dsRequest, dwQueryCond);
                msg.setEvent = dsRequest;
                msg.JobID = "OnQueryTableList2Agent";
                DataSet setReturn = QueryData(msg);
                if (setReturn.Tables.Contains("TableList2Agent"))
                {
                    dtTableList2Agent = setReturn.Tables["TableList2Agent"].Copy();
                }

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return dtTableList2Agent;
        }
        public DataSet GetDataBySM(string TBNAME)
        {
            DataSet dsRequest = new DataSet();
            DataSet setReturn = new DataSet();
            try
            {
                MessageEx msg = new MessageEx(BaseMessage);
                DataRow dwQueryCond = null;
                DataTable dtQueryCond = null;
                dtQueryCond = setQueryCond.Tables[TBNAME + "QueryCond"];
                dwQueryCond = dtQueryCond.NewRow();
                dwQueryCond["QUERYTYPE"] = "QueryOnly";
                dwQueryCond["CONDTYPE"] = "IX_" + TBNAME + "_SM";
                dwQueryCond["SM"] = dwUser["SM"];
                dsRequest = (DataSet)ImportDataTable(dsRequest, dwQueryCond);
                msg.setEvent = dsRequest;
                msg.JobID = "OnQuery" + TBNAME;
                setReturn = QueryData(msg);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return setReturn;
        }
        public DataSet GetDataByAny(string TBNAME, Queue qCond)
        {
            DataSet setReturn = new DataSet();
            try
            {
                DataSet dsRequest = new DataSet();

                MessageEx msg = new MessageEx(BaseMessage);
                DataRow dwQueryCond = null;
                DataTable dtQueryCond = null;
                dtQueryCond = this.setQueryCond.Tables[TBNAME + "QueryCond"];
                dwQueryCond = dtQueryCond.NewRow();
                dwQueryCond["QueryType"] = "QueryOnly";
                dwQueryCond["CONDTYPE"] = "DB_" + TBNAME + "_SELECT_LIKE";
                dsRequest = (DataSet)ImportDataTable(dsRequest, dwQueryCond);
                msg.setEvent = dsRequest;
                msg.JobID = "OnQuery" + TBNAME;
                setReturn = QueryData(msg);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return setReturn;
        }
        private void SetProperty(DataColumn column, string strPropertyName, string PropertyValue)
        {

            if (!column.ExtendedProperties.ContainsKey(strPropertyName))
                column.ExtendedProperties.Add(strPropertyName, PropertyValue);
            else
                column.ExtendedProperties[strPropertyName] = PropertyValue;
        }
        public void EraseProperty(DataTable dtRef, DataTable dtTarget)
        {
            try
            {
                foreach (DataColumn dcExtend in dtRef.Columns)
                {
                    //"XPosition", "YPosition", "Height", "Width", "EditMode", "Lang_Code", "Column_Map_Name"
                    string PropertyName = dcExtend.ColumnName.Trim();
                    if (PropertyName == "Column_Name")
                    {
                        continue;
                    }
                    foreach (DataColumn dcBase in dtTarget.Columns)
                    {
                        if (dcExtend.DataType.FullName == "System.String")
                            SetProperty(dcBase, PropertyName, "");
                        else
                            SetProperty(dcBase, PropertyName, "0");

                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error("DataAccessService.EraseProperty", ex);
            }
        }
        public void SetUpProperty(DataTable dtRef, DataColumn dcBase)
        {
            string PropertyName;
            string PropertyValue;
            try
            {
                var query = from dwRefs in dtRef.AsEnumerable()
                            where dwRefs["Column_Name"].ToString().TrimEnd() == dcBase.ColumnName
                            select dwRefs;

                foreach (DataRow dwExProperty in query)
                {
                    foreach (DataColumn dcProperty in dwExProperty.Table.Columns)
                    {
                        PropertyName = dcProperty.ColumnName.Trim();
                        PropertyValue = dwExProperty[PropertyName].ToString().Trim();
                        SetProperty(dcBase, PropertyName, PropertyValue);
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error("DataAccessService.SetUpProperty", ex);
            }
        }
        public void MakeUpTableGUI(string TBName)
        {
            try
            {
                DataTable dtGUIDesignTime = GlobalDataSet.Tables["GUIDesignTime"];
                DataTable dtSource = this.GlobalDataSet.Tables[TBName];
                EraseProperty(dtGUIDesignTime, dtSource);
                foreach (DataColumn dcBase in dtSource.Columns)
                {
                    SetUpProperty(dtGUIDesignTime, dcBase);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error("DataAccessService.MakeUpTableGUI", ex);
            }
        }
        public void GetTableColumnExtenedProperty(string TBName)
        {
            DataTable dtTableColumnExtenedProperty = new DataTable();
            DataSet dsRequest = new DataSet();
            DataSet setReturn = new DataSet();
            try
            {
                MessageEx msg = new MessageEx(BaseMessage);
                DataRow dwQueryCond = this.setQueryCond.Tables["TableColumnExtenedPropertyQueryCond"].NewRow();
                dwQueryCond["QUERYTYPE"] = "QueryOnly";
                dwQueryCond["CONDTYPE"] = "IX_TableColumnExtenedProperty_TBNAME";
                dwQueryCond["SM"] = dwUser["SM"];
                dwQueryCond["TBNAME"] = TBName;
                dsRequest = (DataSet)ImportDataTable(dsRequest, dwQueryCond);
                msg.setEvent = dsRequest;
                msg.JobID = "OnQueryTableColumnExtenedProperty";
                setReturn = QueryData(msg);
                if (setReturn.Tables.Contains("TableColumnExtenedProperty"))
                {
                    dtTableColumnExtenedProperty = setReturn.Tables["TableColumnExtenedProperty"].Copy();
                }
                string TBCName = "TableColumnExtenedProperty";
                if (GlobalDataSet.Tables.Contains(TBCName))
                {
                    DataRow[] dwTemps = GlobalDataSet.Tables[TBCName].Select("TBNAME='" + TBName + "'");
                    foreach (DataRow dwTemp in dwTemps)
                    {
                        dwTemp.Delete();
                    }
                    GlobalDataSet.Tables[TBCName].AcceptChanges();
                }
                GlobalDataSet.Merge(dtTableColumnExtenedProperty);
            }
            catch (Exception ex)
            {
                Tracer.Error("DataAccessService.GetTableColumnExtenedProperty", ex);
            }

        }
        public void GetTableStructure(string TBNAME, MessageEx BaseMessage)
        {
            try
            {
                DataSet dsRequest = new DataSet();
                MessageEx msgRequest = new MessageEx(BaseMessage);
                DataTable dtQueryCond = null;
                DataRow dwQueryCond = null;

                dtQueryCond = new DataTable(TBNAME);
                dtQueryCond.Columns.Add("SM", System.Type.GetType("System.String"));
                dtQueryCond.Columns.Add("QUERYTYPE", System.Type.GetType("System.String"));
                dtQueryCond.Columns.Add("CONDTYPE", System.Type.GetType("System.String"));
                dwQueryCond = dtQueryCond.NewRow();
                dwQueryCond["SM"] = "1";
                dwQueryCond["QUERYTYPE"] = "QueryOnly";
                dwQueryCond["CONDTYPE"] = "DB_" + TBNAME + "_STRUCTURE";
                dsRequest = (DataSet)ImportDataTable(dsRequest, dwQueryCond);
                msgRequest.setEvent = dsRequest;
                msgRequest.JobID = "OnQueryTableStructure";
                DataSet setReturn = QueryData(msgRequest);
                GlobalDataSet.Merge(setReturn.Tables[TBNAME]);
            }
            catch (Exception ex)
            {
                Tracer.Error("DataAccessService.GetTableStructure", ex);
            }
        }
        public void MakeUpTableEx(string TBName)
        {
            try
            {
                DataTable dtTableColumnExtenedProperty = GlobalDataSet.Tables["TableColumnExtenedProperty"];
                DataTable dtSource = this.GlobalDataSet.Tables[TBName];
                EraseProperty(dtTableColumnExtenedProperty, dtSource);

                foreach (DataColumn dcBase in dtSource.Columns)
                {
                    SetUpProperty(dtTableColumnExtenedProperty, dcBase);
                }
                dtSource.ExtendedProperties["MakeUp"] = "YES";
            }
            catch (Exception ex)
            {
                Tracer.Error("DataAccessService.MakeUpTableEx", ex);
            }

        }
        public DataRow UpdateDataRow(DataRow dwTarget, DataRow dwSource, Queue ForeignKeyList, Queue PrimaryKeyList)
        {
            string TargetColumnName = "";
            string SourceColumnName = "";
            try
            {
                //for (int i = 0; i < ForeignKeyList.Count; i++)
                while (ForeignKeyList.Count > 0)
                {
                    TargetColumnName = (string)ForeignKeyList.Dequeue();
                    SourceColumnName = (string)PrimaryKeyList.Dequeue();
                    if (dwTarget.Table.Columns.Contains(TargetColumnName) && dwSource.Table.Columns.Contains(SourceColumnName))
                    {
                        dwTarget[TargetColumnName] = dwSource[SourceColumnName];
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.Source, ex);
            }
            dwTarget.AcceptChanges();
            return dwTarget;
        }
        public DataRow MapDataRow(string QueryType, string CONDTYPE, DataRow dwTarget, DataRow dwSource,
        List<string> ForeignKeyList, List<string> PrimaryKeyList, bool Empty)
        {
            string TargetColumnName = "";
            string SourceColumnName = "";
            string TargetTable = dwTarget.Table.TableName;
            Queue RPrimaryKeyList = new Queue();
            Queue RForeignKeyList = new Queue();
            try
            {
                if (dwTarget == null)
                {
                    if (TargetTable.Contains("QueryCond"))
                    {
                        dwTarget = this.setQueryCond.Tables[TargetTable].NewRow();
                    }
                    else
                    {
                        dwTarget = setGlobal.Tables[TargetTable].NewRow();
                    }
                }

                if (dwTarget.Table.Columns.Contains("QueryType"))
                {
                    dwTarget["QueryType"] = QueryType;
                    dwTarget["CONDTYPE"] = CONDTYPE;
                }

                if (ForeignKeyList == null)
                {
                    foreach (DataColumn dcTemp in dwSource.Table.Columns)
                    {
                        string Column = dcTemp.ColumnName.ToString().Trim();
                        if (dwTarget.Table.Columns.Contains(Column))
                        {
                            if (dwTarget[Column].ToString().Trim() == "")
                            {
                                dwTarget[Column] = dwSource[Column];
                            }
                        }
                    }
                    return dwTarget;
                }
                int count = ForeignKeyList.Count;
                for (int i = 0; i < count; i++)
                {
                    TargetColumnName = (string)PrimaryKeyList[i];
                    SourceColumnName = (string)ForeignKeyList[i];
                    if (dwTarget.Table.Columns.Contains(TargetColumnName)
                        && dwSource.Table.Columns.Contains(SourceColumnName))
                    {
                        if (dwTarget[TargetColumnName].ToString().Trim() == "")
                        {
                            dwTarget[TargetColumnName] = dwSource[SourceColumnName];
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(".MapDataRow:", ex);
            }

            return dwTarget;
        }
        public void MapDataRow(ref DataRow dwTarget, DataRow dwSource, List<string> ForeignKeyList, List<string> PrimaryKeyList,
            bool blForce)
        {
            string TargetColumnName = "";
            string SourceColumnName = "";
            string TargetTable = dwTarget.Table.TableName;
            Queue RPrimaryKeyList = new Queue();
            Queue RForeignKeyList = new Queue();
            try
            {
                if (ForeignKeyList == null)
                {
                    foreach (DataColumn dcTemp in dwSource.Table.Columns)
                    {
                        string Column = dcTemp.ColumnName.ToString().Trim();
                        if (dwTarget.Table.Columns.Contains(Column))
                        {
                            if (dwTarget[Column].ToString().Trim() == "")
                            {
                                dwTarget[Column] = dwSource[Column];
                            }
                        }
                    }
                    return;
                }
                int count = ForeignKeyList.Count;
                for (int i = 0; i < count; i++)
                {
                    TargetColumnName = (string)PrimaryKeyList[i];
                    SourceColumnName = (string)ForeignKeyList[i];
                    if (dwTarget.Table.Columns.Contains(TargetColumnName)
                        && dwSource.Table.Columns.Contains(SourceColumnName))
                    {
                        if (blForce)
                        {
                            dwTarget[TargetColumnName] = dwSource[SourceColumnName];
                        }
                        continue;
                        if (dwTarget[TargetColumnName].ToString().Trim() == "")
                        {
                            dwTarget[TargetColumnName] = dwSource[SourceColumnName];
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(".MapDataRow:", ex);
            }

            return;
        }
        public DataRow MapDataRow(string QueryType, string CONDTYPE, string TargetTable, DataRow dwTarget,
                    DataRow dwSource, Queue SourceKeyList, Queue TargetKeyList)
        {

            string TargetColumnName = "";
            string SourceColumnName = "";
            try
            {
                if (dwTarget == null)
                {
                    if (TargetTable.EndsWith("QueryCond"))
                    {
                        dwTarget = setQueryCond.Tables[TargetTable].NewRow();
                    }
                    else
                    {
                        dwTarget = GlobalDataSet.Tables[TargetTable].NewRow();
                    }
                }
                if (dwTarget.Table.TableName.EndsWith("QueryCond"))
                {
                    dwTarget["QueryType"] = QueryType;
                    dwTarget["CONDTYPE"] = CONDTYPE;
                }

                if (SourceKeyList == null)
                {
                    foreach (DataColumn dcTemp in dwSource.Table.Columns)
                    {
                        string Column = dcTemp.ColumnName.ToString().Trim();
                        if (dwTarget.Table.Columns.Contains(Column))
                        {
                            dwTarget[Column] = dwSource[Column];
                        }
                    }
                }
                else
                {
                    while (SourceKeyList.Count > 0)
                    {
                        TargetColumnName = (string)TargetKeyList.Dequeue();
                        SourceColumnName = (string)SourceKeyList.Dequeue();
                        if (dwTarget.Table.Columns.Contains(TargetColumnName)
                            && dwSource.Table.Columns.Contains(SourceColumnName))
                        {
                            dwTarget[TargetColumnName] = dwSource[SourceColumnName];
                        }
                        if (TargetColumnName == "KREAL")
                        {
                            if (CONDTYPE == "IX_GTPREDef_Table"
                                || CONDTYPE == "IX_GoodsMasterKeyRelation_Key")
                            {
                                dwTarget[TargetColumnName] = dwSource.Table.TableName;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            if (QueryType == "CreateByQuery")
            {
                if (dwTarget.Table.Columns.Contains("UID"))
                {
                    dwTarget["UID"] = "";
                }
            }
            return dwTarget;
        }

        public void MapDataRow(string QueryType, string CONDTYPE, string TargetTable, ref DataRow dwTarget,
            DataRow dwSource, Queue SourceKeyList, Queue TargetKeyList, bool blForceTr = false)
        {
            string TargetColumnName = "";
            string SourceColumnName = "";
            try
            {
                if (dwTarget == null)
                {
                    if (TargetTable.EndsWith("QueryCond"))
                    {
                        dwTarget = setQueryCond.Tables[TargetTable].NewRow();
                    }
                    else
                    {
                        dwTarget = GlobalDataSet.Tables[TargetTable].NewRow();
                    }
                }
                if (dwTarget.Table.TableName.EndsWith("QueryCond"))
                {
                    dwTarget["QueryType"] = QueryType;
                    dwTarget["CONDTYPE"] = CONDTYPE;
                }

                if (SourceKeyList == null)
                {
                    foreach (DataColumn dcTemp in dwSource.Table.Columns)
                    {
                        string Column = dcTemp.ColumnName.ToString().Trim();
                        if (dwTarget.Table.Columns.Contains(Column))
                        {
                            dwTarget[Column] = dwSource[Column];
                        }
                    }
                }
                else
                {
                    while (SourceKeyList.Count > 0)
                    {
                        TargetColumnName = (string)TargetKeyList.Dequeue();
                        SourceColumnName = (string)SourceKeyList.Dequeue();
                        if (dwTarget.Table.Columns.Contains(TargetColumnName)
                            && dwSource.Table.Columns.Contains(SourceColumnName))
                        {
                            dwTarget[TargetColumnName] = dwSource[SourceColumnName];
                        }
                        if (TargetColumnName == "KREAL")
                        {
                            if (CONDTYPE == "IX_GTPREDef_Table"
                                || CONDTYPE == "IX_GoodsMasterKeyRelation_Key")
                            {
                                dwTarget[TargetColumnName] = dwSource.Table.TableName;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            if (QueryType == "CreateByQuery")
            {
                if (dwTarget.Table.Columns.Contains("UID"))
                {
                    dwTarget["UID"] = "";
                }
            }
        }
        public DataRow MapDataRow(string QueryType, string CONDTYPE, string TargetTable,
               DataRow dwSource, Queue ForeignKeyList, Queue PrimaryKeyList, bool Empty)
        {
            DataRow dwTarget = null;
            string TargetColumnName = "";
            string SourceColumnName = "";
            Queue RPrimaryKeyList = new Queue();
            Queue RForeignKeyList = new Queue();
            try
            {
                if (TargetTable.Contains("QueryCond"))
                {
                    dwTarget = setQueryCond.Tables[TargetTable].NewRow();
                }
                else
                {
                    dwTarget = setGlobal.Tables[TargetTable].NewRow();
                }

                if (dwTarget.Table.Columns.Contains("QueryType"))
                {
                    dwTarget["QueryType"] = QueryType;
                    dwTarget["CONDTYPE"] = CONDTYPE;
                }

                if (ForeignKeyList == null)
                {
                    foreach (DataColumn dcTemp in dwSource.Table.Columns)
                    {
                        string Column = dcTemp.ColumnName.ToString().Trim();
                        if (dwTarget.Table.Columns.Contains(Column))
                        {
                            if (dwTarget[Column].ToString().Trim() == "")
                            {
                                dwTarget[Column] = dwSource[Column];
                            }
                        }
                    }
                    return dwTarget;
                }

                while (ForeignKeyList.Count > 0)
                {
                    TargetColumnName = (string)PrimaryKeyList.Dequeue();
                    SourceColumnName = (string)ForeignKeyList.Dequeue();
                    if (dwTarget.Table.Columns.Contains(TargetColumnName)
                        && dwSource.Table.Columns.Contains(SourceColumnName))
                    {
                        if (dwTarget[TargetColumnName].ToString().Trim() == "")
                        {
                            dwTarget[TargetColumnName] = dwSource[SourceColumnName];
                        }
                    }
                    if (!Empty)
                    {
                        RPrimaryKeyList.Enqueue(TargetColumnName);
                        RForeignKeyList.Enqueue(SourceColumnName);
                    }
                }
                if (!Empty)
                {
                    PrimaryKeyList = RPrimaryKeyList;
                    ForeignKeyList = RForeignKeyList;

                }
            }
            catch (Exception ex)
            {
                Tracer.Error(".BuildSQLParameters:", ex);
            }

            return dwTarget;
        }

        public void MapDataRow(ref DataRow dwTarget, DataRow dwReference, bool blGDKEY)
        {
            string TTBName = dwTarget.Table.TableName.Replace("QueryCond", "");
            string STBName = dwReference.Table.TableName.Replace("QueryCond", "");

            string GDKEYList = "SM;GTPRE;GTKEY;GDKEY;";
            try
            {
                foreach (DataColumn dcTemp in dwReference.Table.Columns)
                {
                    string Column = dcTemp.ColumnName.ToString().Trim();
                    if (!blGDKEY)
                    {
                        if (GDKEYList.Contains(Column + ";"))
                            continue;
                    }
                    if (dwTarget.Table.Columns.Contains(Column))
                    {
                        dwTarget[Column] = dwReference[Column];
                    }
                }
                if (dwTarget.Table.Columns.Contains(TTBName + "Key")
                    && dwReference.Table.Columns.Contains(STBName + "Key")
                    )
                {
                    dwTarget[TTBName + "Key"] = dwReference[STBName + "Key"];
                }
                if (dwTarget.Table.Columns.Contains(TTBName + "KeyID")
                      && dwReference.Table.Columns.Contains(STBName + "ID")
                      )
                {
                    dwTarget[TTBName + "KeyID"] = dwReference[STBName + "ID"];
                }
            }
            catch (Exception ex)
            {
                Tracer.Error("MainWindow.MapDataRow", ex);
            }
        }
    }
}
